<template>
  <div id="addColumn" class="container">
    <h3 class="title">
      <span />
      编辑栏目
    </h3>
    <el-button
      size="small"
      icon="el-icon-arrow-left"
      type="primary"
      class="back"
      @click="prev"
    >
      返回
    </el-button>
    <el-form
      ref="addForm"
      :model="addForm"
      :rules="columnRules"
      inline
      label-width="100px"
      class="addForm"
    >
      <div class="left">
        <h5 class="title">
          <span />
          基本信息
        </h5>
        <el-form-item label="上级栏目:" prop="parent_id">
          <el-cascader
            v-model="addForm.parent_id"
            :options="columnList"
            :props="{ label: 'title', value: 'id', checkStrictly: true }"
            :show-all-levels="false"
            @change="changeColumn"
          />
        </el-form-item>

        <el-form-item
          v-if="parent_websiteId != 0"
          label="父站点栏目:"
          prop="parent_map"
        >
          <el-cascader
            v-model="addForm.parent_map"
            :options="parentColumn"
            :props="{ label: 'title', value: 'id', checkStrictly: true }"
            :show-all-levels="false"
            @change="changeParentColumn"
          />
        </el-form-item>
        <el-form-item v-if="parent_websiteId == 0" label="类型:" prop="type">
          <el-radio-group v-model="addForm.type" @change="raidoChange">
            <el-radio :label="1">列表栏目</el-radio>
            <el-radio :label="2">频道封面</el-radio>
            <el-radio :label="3">跳转链接</el-radio>
            <el-radio :label="4">单页面</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="栏目名称:" prop="title">
          <el-input v-model="addForm.title" />
        </el-form-item>
        <div v-if="parent_websiteId == 0">
          <el-form-item
            v-if="addForm.type == 1 || addForm.type == 4"
            label="栏目别名:"
          >
            <el-input
              v-model="addForm.alias"
              placeholder="别名由英文字母数字和 - _ / 组成并以 / 开头"
            />
          </el-form-item>
          <el-form-item v-if="addForm.type == 3" label="访问地址" prop="alias">
            <el-input
              v-model="addForm.alias"
              placeholder="访问地址以http://或者https://开头"
            />
          </el-form-item>
          <el-form-item v-if="addForm.type != 3" label="模型:" prop="module_id">
            <el-select v-model="addForm.module_id" disabled>
              <el-option
                v-for="item in moduleList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <div v-if="addForm.type == 1 || addForm.type == 4">
            <el-form-item label="列表页模板:" prop="list_tpl">
              <el-select v-model="addForm.list_tpl" @change="changeList">
                <el-option
                  v-for="item in tempList"
                  :key="item.id"
                  :label="item.file"
                  :value="item.file"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="详情页模板:"
              :prop="addForm.type == 1 ? 'detail_tpl' : ' '"
            >
              <el-select
                v-model="addForm.detail_tpl"
                clearable
                @change="changeDetail"
              >
                <el-option
                  v-for="item in detailTempList"
                  :key="item.id"
                  :label="item.file"
                  :value="item.file"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="排序">
          <el-input v-model="addForm.sort" />
        </el-form-item>
        <el-form-item label="描述:">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :autosize="{ minRows: 5, maxRows: 8 }"
          />
        </el-form-item>
        <el-form-item v-if="addForm.type == 4" label="内容">
          <div>
            <myTinymce
              ref="myTinymce"
              :tinymce-html="addForm.content"
              :show-btn="showBtn"
            />
          </div>
        </el-form-item>
        <el-form-item
          v-if="addForm.type != 4"
          label=" "
          style="margin-top: 6px"
        >
          <el-button type="primary" class="save" size="small" @click="submit()">
            保 存
          </el-button>
          <el-button size="small" class="exit" @click="prev">返 回</el-button>
        </el-form-item>
      </div>
      <div class="right">
        <h5 class="title">
          <span />
          SEO设置
        </h5>
        <el-form-item label="Title:">
          <el-input v-model="addForm.seo_title" />
        </el-form-item>
        <el-form-item label="Keyword:">
          <el-input v-model="addForm.seo_keywords" />
        </el-form-item>
        <el-form-item label="Description:">
          <el-input v-model="addForm.seo_description" type="textarea" />
        </el-form-item>
        <h5 class="title">
          <span />
          附件信息
        </h5>
        <el-form-item label="搜索支持:" required>
          <el-radio-group v-model="addForm.is_search">
            <el-radio :label="1">支持</el-radio>
            <el-radio :label="2">不支持</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="副标题:">
          <el-input v-model="addForm.sub_title" />
        </el-form-item>
        <el-form-item label="简介:">
          <el-input v-model="addForm.desc" />
        </el-form-item>
        <h5 class="title">
          <span />
          栏目图片
        </h5>
        <Attachment
          ref="attachment"
          :dialog-show.sync="dialogShow"
          :attachment-type="attachmentType"
          @func="getData"
        />
        <el-form-item size="small" label="缩略图:">
          <div class="attachment_imgBox" @click="openList('thumbnail')">
            <img
              v-if="addForm.thumbnail"
              :src="thumbnail"
              class="attachmentImg"
            />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.thumbnail" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(1)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-form-item>
        <el-form-item size="small" label="banner图:">
          <div class="attachment_imgBox" @click="openList('banner')">
            <img v-if="addForm.banner" :src="banner" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.banner" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(2)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-form-item>
        <!-- <h5 class="title">
          <span />
          自定义字段
        </h5>
        <div class="fieldBox">
          <el-form-item
            label=""
            v-for="(item, index) in fieldList"
            :key="item.key"
          >
            <el-col :span="5">
              <el-input v-model="item.key" placeholder="字段名"></el-input>
            </el-col>
            <el-col class="line" :span="1">:</el-col>
            <el-col :span="11">
              <el-input v-model="item.value" placeholder="字段值"></el-input>
            </el-col>
            <el-col v-if="index != 0" class="delField" :span="3">
              <span @click="delField(item, index)">删除</span>
            </el-col>
          </el-form-item>
          <div class="add-field-btn" @click="handleAddField">
            <i class="el-icon-plus" />
            添加字段
          </div>
        </div> -->
        <h5 class="title">
          <span />
          审核设置
        </h5>
        <el-form-item label="审核：">
          <el-radio-group v-model="addForm.need_check">
            <el-radio :label="1">需要审核</el-radio>
            <el-radio :label="2">无需审核</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-table v-if="addForm.need_check == 1" :data="addForm.check_list">
          <el-table-column
            label="审核步骤"
            type="index"
            width="100"
            align="center"
          />
          <el-table-column label="审核人" align="center">
            <template slot-scope="scope">
              <ChoiceUser :key="scope.row.id" v-model="scope.row.check_users" />
            </template>
          </el-table-column>
          <el-table-column label="审核方式" width="200" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.examine_mode">
                <el-radio :label="1">或签</el-radio>
                <el-radio :label="2">会签</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDeleteTable(scope)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div
          v-if="addForm.need_check == 1"
          class="add-table-btn"
          @click="handleAddTable"
        >
          <i class="el-icon-plus" />
          添加
        </div>
        <el-form-item
          v-if="addForm.type == 4"
          label=" "
          style="margin-top: 6px"
        >
          <el-button type="primary" class="save" size="small" @click="submit()">
            保 存
          </el-button>
          <el-button size="small" class="exit" @click="prev">返 回</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import columnApi from '@/api/column'
import moduleApi from '@/api/module'
import tempApi from '@/api/theme'
import { getToken } from '@/utils/auth'
import myTinymce from '@/components/scEditor/'
import ChoiceUser from '@/components/choiceUser'
var token = 'Bearer ' + getToken()
import { nanoid } from 'nanoid'

export default {
  components: { myTinymce, ChoiceUser },
  data() {
    return {
      showBtn: false,
      attachmentType: '',
      columnList: [], // 栏目列表
      parentColumn: [],
      defaultKeys: [],
      attachmentLimit: 10,
      dialogShow: false,
      attachmentData: [],
      imagelist: [],
      imagetype: '',
      thumbnail: '',
      banner: '',
      myHeaders: { Authorization: token },
      headers: {},
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      id: '',
      website_id: '',
      lang: '',
      moduleList: [],
      tempList: [],
      detailTempList: [],
      // fieldNum: 1,
      // fieldList: [{ key: 'custom', value: '' }],
      parent_id: '',
      addForm: {
        id: '',
        parent_id: '',
        title: '',
        website_id: '',
        alias: '',
        module_id: '',
        list_tpl: '',
        type: '',
        description: '',
        desc: '',
        detail_tpl: '',
        seo_description: '',
        seo_keywords: '',
        seo_title: '',
        thumbnail: '',
        lang: '',
        banner: '',
        sort: '',
        sub_title: '',
        content: '',
        is_search: 2,
        parent_map: '',
        parent_map: '',
        need_check: 1,
        check_list: []
      },
      tempType: '',
      columnRules: {
        type: [{ required: 'true', message: '请选择类型', trigger: 'change' }],
        parent_map: [
          { required: 'true', message: '请选择父级站点栏目', trigger: 'change' }
        ],
        title: [
          { required: 'true', message: '请输入栏目名称', trigger: 'blur' }
        ],
        alias: [
          { required: 'true', message: '请输入自定义名称', trigger: 'blur' }
        ],
        module_id: [
          { required: 'true', message: '请选择模型', trigger: 'change' }
        ],
        list_tpl: [
          { required: 'true', message: '请选择列表页模板', trigger: 'change' }
        ],
        detail_tpl: [
          { required: 'true', message: '请选择详情页模板', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    }
  },
  watch: {
    siteId1(val, value) {
      // this.website_id = val
      if (value) {
        this.$router.push({ name: 'Category' })
      }
      this.getMould()
      this.getTemp()
    }
  },
  created() {
    this.id = this.$route.query.id
    this.website_id = this.$route.query.website_id
    this.lang = this.$route.query.lang
    this.parent_websiteId = this.$store.getters.parentId
    this.getMould()
    this.getTemp()
    this.getDetailTemp()
    this.getColumnList()
    this.getParentColumn()
    this.getColumnInfo()
  },
  methods: {
    // 删除字段
    delField(item, index) {
      this.fieldList.splice(index, 1)
    },
    // 添加字段
    handleAddField() {
      const keyStr = 'custom' + this.fieldNum
      this.fieldList.push({
        key: keyStr,
        value: ''
      })
      this.fieldNum++
    },
    // 移除图片数据
    handleRemove(type) {
      if (type == 1) {
        // 移除缩略图
        this.addForm.thumbnail = ''
        this.thumbnail = ''
      } else {
        // 移除banner图
        this.addForm.banner = ''
        this.banner = ''
      }
    },
    handleDeleteTable(row) {
      if (this.addForm.check_list.length > 1) {
        this.addForm.check_list.splice(row.$index, 1)
      } else {
        this.$message.error('最少保留一条审核记录')
      }
    },
    // 添加审核
    handleAddTable() {
      this.addForm.check_list.push({
        id: nanoid(),
        check_users: [],
        examine_mode: 1
      })
    },
    getData(data) {
      if (data.length > 1) {
        this.$message.error('最多只能选择一张图片')
      } else {
        if (this.imagetype == 'thumbnail') {
          this.addForm.thumbnail = data[0].id
          this.thumbnail = data[0].url
        } else if (this.imagetype == 'banner') {
          this.addForm.banner = data[0].id
          this.banner = data[0].url
        }
        this.dialogShow = false
      }
    },
    // 打开附件弹窗
    openList(val) {
      this.dialogShow = true
      this.attachmentType = 2
      this.$nextTick(() => {
        this.$refs.attachment.getAttachmentList()
        this.$refs.attachment.$refs.AttachmentCate.getCateList(0)
      })
      this.imagetype = val
      // this.getAttachmentList()
    },
    changeColumn(val) {
      this.defaultKeys = []
      val.forEach(el => {
        this.defaultKeys.push(el.toString())
      })
      this.parent_id = val[val.length - 1]
    },
    // 切换父级站点栏目
    changeParentColumn(val) {
      // this.addForm.parent_map = val[val.length - 1]
    },
    // 父级栏目列表
    getParentColumn() {
      const val = {
        website_id: this.$store.getters.parentId,
        lang: this.lang
      }
      columnApi.columnList(val).then(res => {
        this.parentColumn = res.data
        this.getTypeList(this.parentColumn)
      })
    },
    // 栏目列表
    getColumnList() {
      // this.website_id = this.siteId
      const val = {
        website_id: this.website_id,
        lang: this.lang
      }
      columnApi.columnList(val).then(res => {
        this.columnList = res.data
        this.columnList.unshift({
          title: '作为一级栏目',
          id: 0,
          children: []
        })
        this.getTypeList(this.columnList)
      })
    },

    // 递归将children为空的数组置位undefined
    getTypeList(arr) {
      arr.forEach(el => {
        if (el.children.length > 0) {
          this.getTypeList(el.children)
        } else {
          el.children = undefined
        }
      })
      // this.addForm.parent_id = this.parent_id
    },
    changeList(val) {},
    changeDetail(val) {},

    //   模型列表
    getMould() {
      moduleApi.moduleList().then(res => {
        this.moduleList = res.data
      })
    },
    // 列表栏目下的列表页模板
    getTemp() {
      const val = {
        website_id: this.website_id,
        lang: this.lang,
        type: this.tempType
      }
      tempApi.tempFiles(val).then(res => {
        this.tempList = res.data
      })
    },
    // 列表栏目下的列表页模板
    getDetailTemp() {
      const val = {
        website_id: this.website_id,
        lang: this.lang,
        type: 2
      }
      tempApi.tempFiles(val).then(res => {
        this.detailTempList = res.data
      })
    },
    // 栏目详情
    getColumnInfo() {
      const val = {
        website_id: this.website_id,
        id: this.id
      }
      columnApi.columnInfo(val).then(res => {
        const item = res.data
        const checkList = item.check_list.map(row => ({
          examine_mode: row.examine_mode,
          check_users: row.check_users.split(',')
        }))
        // if (item.field_list) {
        //   this.fieldList = item.field_list
        // }

        // this.addForm.parent_id = 1
        if (this.parent_websiteId == 0) {
          this.addForm = {
            id: item.id,
            parent_id: [item.parent_id],
            title: item.title,
            website_id: item.website_id,
            alias: item.alias,
            module_id: item.module_id,
            list_tpl: item.list_tpl,
            type: item.type,
            desc: item.desc,
            description: item.description,
            detail_tpl: item.detail_tpl,
            seo_description: item.seo_description,
            seo_keywords: item.seo_keywords,
            seo_title: item.seo_title,
            thumbnail: item.thumbnail ? item.thumbnail.id : null,
            lang: this.lang,
            banner: item.banner ? item.banner.id : null,
            sort: item.sort,
            sub_title: item.sub_title,
            content: item.content,
            is_search: item.is_search,
            need_check: item.need_check,
            check_list: checkList
          }
        } else {
          this.addForm = {
            id: item.id,
            parent_id: [item.parent_id],
            parent_map: item.parent_path,
            title: item.title,
            website_id: item.website_id,
            desc: item.desc,
            description: item.description,
            seo_description: item.seo_description,
            seo_keywords: item.seo_keywords,
            seo_title: item.seo_title,
            thumbnail: item.thumbnail ? item.thumbnail.id : null,
            lang: this.lang,
            banner: item.banner ? item.banner.id : null,
            sort: item.sort,
            sub_title: item.sub_title,
            is_search: item.is_search,
            need_check: item.need_check,
            check_list: checkList
          }
        }

        if (item.type == 1) {
          this.tempType = 1
          this.getTemp()
        } else if (item.type == 4) {
          this.tempType = 3
          this.getTemp()
        }
        this.thumbnail = item.thumbnail ? item.thumbnail.url : ''
        this.banner = item.banner ? item.banner.url : ''
        const pid = item.path.split('-')
        const arr = []
        if (pid.length > 2) {
          pid.shift()
          pid.pop()
          pid.forEach(el => {
            arr.push(parseInt(el))
          })
          this.addForm.parent_id = arr
        } else if (pid.length == 2) {
          this.addForm.parent_id = [0]
        }
      })
    },
    // 切换单选按钮
    raidoChange(val) {
      if (val == 1) {
        this.tempType = 1
        this.getTemp()
      } else if (val == 4) {
        this.tempType = 3
        this.getTemp()
      }
    },
    // 提交
    submit() {
      // 开启审核时校验
      let checkTable = []
      if (this.addForm.need_check == 1) {
        checkTable = this.addForm.check_list.map(item => ({
          check_users: item.check_users.join(','),
          examine_mode: item.examine_mode
        }))
        const checkIndex = checkTable.findIndex(
          item => !item.check_users || !item.examine_mode
        )
        if (checkIndex >= 0 || !this.addForm.check_list.length) {
          this.$message.error('请完善审核流程')
          return
        }
      }

      this.$refs.addForm.validate(valid => {
        if (valid) {
          // this.addForm.field_list = this.fieldList
          if (this.addForm.parent_id.length) {
            this.addForm.parent_id =
              this.addForm.parent_id[this.addForm.parent_id.length - 1]
          }
          this.addForm.content = this.$refs.myTinymce
            ? this.$refs.myTinymce.value
            : ''
          columnApi
            .columnUpdate({ ...this.addForm, check_list: checkTable })
            .then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.$router.push({
                  name: 'Category',
                  query: { key: res.data.path }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    },
    prev() {
      this.$router.push({ name: 'Category' })
    }
  }
}
</script>
<style lang="scss">
#addColumn {
  .el-form-item {
    width: 100%;
    .el-form-item__content {
      width: calc(100% - 150px);
      .el-select,
      .el-cascader {
        width: 100%;
      }
    }
  }
}
.el-cascader-node.in-active-path,
.el-cascader-node.is-active,
.el-cascader-node.is-selectable.in-checked-path {
  color: #f84311 !important;
}
.el-radio__input.is-checked .el-radio__inner {
  background-color: #f84311 !important;
  border-color: #f84311 !important;
}
.el-radio__inner:hover {
  border-color: #f84311 !important;
}
</style>
<style scoped lang="scss">
.add-table-btn {
  width: 100%;
  border: 1px dashed #dcdfe6;
  font-size: 14px;
  text-align: center;
  line-height: 40px;
  margin-top: 20px;
  cursor: pointer;
}
.addForm {
  background-color: #fff;
  padding: 50px 20px 20px;

  display: flex;
  justify-content: space-between;
  .left {
    width: 50%;
  }
  .right {
    width: 48%;
  }
  h5.title {
    height: 40px;
    line-height: 40px;
    border-left: solid 4px #f84311;
    background-color: #f5f5f5;
    font-size: 15px;
    color: #555;
    padding-left: 20px;
    margin-bottom: 20px;
  }
  .avatar {
    width: 100px;
  }
}
#app .el-form .btn {
  text-align: left;
  margin-left: 150px;
}
.back {
  position: absolute;
  right: 36px;
  top: 28px;
}
.attachment_imgBox .img-actions {
  position: absolute;
  background: rgba($color: #000000, $alpha: 0.3);
  top: 1px;
  left: 3px;
  transition: all 0.5s;
  -moz-transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -o-transition: all 0.5s;
  opacity: 0;
}
.attachment_imgBox .img-actions > span {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.attachment_imgBox .img-actions > span > i {
  color: #f00;
  font-size: 22px;
}
.attachment_imgBox:hover .img-actions {
  opacity: 1;
}
.line {
  text-align: center;
}
.add-field-btn {
  display: inline-block;
  padding: 0 20px;
  border: 1px dashed #dcdfe6;
  font-size: 14px;
  text-align: center;
  line-height: 40px;
  margin-top: 0px;
  cursor: pointer;
}
.delField {
  display: inline-block;
  padding: 0 20px;
  border: 1px dashed #dcdfe6;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  margin-top: 0px;
  cursor: pointer;
  margin-left: 10px;
  vertical-align: middle;
}
.fieldBox {
  padding: 0 0 20px 0;
}
</style>
